/*
 * iShopPlace Project.
 */
package ishopplace.view.validator.regex;

import java.util.regex.Pattern;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import javax.faces.FacesException;

/**
 * The JSF validator class for RegexValidator.
 * <p>
 * This validator is to validate the input value using a regular expression,
 * which is the only parameter associated with this validator:
 * 
 * @author <a href="mailto:derek@derekshen.com">Derek Y. Shen</a>
 */
public class RegexValidator implements Validator {
	private static final String DEFAULT_ERROR_MESSAGE = 
		"Validator Error: invalid input value";
	
	//the regular expression
	private String regex;
	
	//erro message
	private String errorMsg;
	
	/**
	 * Main method to implement for <code>Validator</code>
	 */
	public void validate(FacesContext context, UIComponent component, Object value) {
		String valueStr = null;
		try {
			valueStr = (String)value;
		} catch (Exception e) {
			throw new FacesException("RegexValidator can only be attached to component UIInput.");
		}
		
		if (!Pattern.matches(regex, valueStr)) {
			if (this.errorMsg == null) {
				this.errorMsg = DEFAULT_ERROR_MESSAGE;
			}
			
			FacesMessage message = 
				new FacesMessage(FacesMessage.SEVERITY_ERROR, this.errorMsg, this.errorMsg);
			throw new ValidatorException(message);
		}
	}
	
	public void setRegex(String newRegex) {
		this.regex = newRegex;
	}
	
	public void setErrorMsg(String newErrorMsg) {
		this.errorMsg = newErrorMsg;
	}
}

